package model

import (
	"os"
	"io/ioutil"
	"fmt"
	"bytes"
	"strings"
	"global/structs"
	"github.com/go-xorm/xorm"
)

type trustCoinModel struct {}

var TrustCoinModel = new(trustCoinModel)

// 插入数据到新表
func (trustCoinModel) InsertIntoBackupTable(sess *xorm.Session, tableName string, items []structs.TrustCoin) (int64, error) {
	return sess.Table(tableName).Insert(items)
}

// 删除原表数据
func (trustCoinModel) RemoveFromOriginalTable(sess *xorm.Session, ids []int) (int64, error) {
	trustCoin := new(structs.TrustCoin)
	return sess.In("id", ids).Delete(trustCoin)
}

// 获取
func (trustCoinModel) GetItems(count int64) ([]structs.TrustCoin, error) {
	items := make([]structs.TrustCoin, 0)
	err := MainDB.Where("status in (2, 3)").Asc("id").Limit(int(count)).Find(&items)
	if err != nil {
		return nil, err
	}
	return items, nil
}

// 获取表中总记录数
func (trustCoinModel) GetCount(tableName string) (int64, error) {
	trustCoin := new(structs.TrustCoin)
	return MainDB.Table(tableName).Count(trustCoin)
}

// 检查表是否存在
func (trustCoinModel) IsTableExists(newTableName string) (bool, error) {
	exists, err := MainDB.IsTableExist(newTableName)
	if err != nil {
		return false, err
	}
	return exists, nil
}

// 创建一个表
func (self trustCoinModel) CreateTable(tableName string) (bool, error) {
	sql, err := self.getSqlFile()
	if err != nil {
		return false, err
	}
	sql = fmt.Sprintf(sql, tableName)

	buf := new(bytes.Buffer)
	buf.ReadFrom(strings.NewReader(sql))

	res, err := MainDB.Import(buf)
	if err != nil {
		return false, err
	}

	return len(res) > 0, nil
}

func (trustCoinModel) getSqlFile() (string, error) {
	file, err := os.Open("./conf/trust_coin.sql")
	if err != nil {
		return "", err
	}
	data, err := ioutil.ReadAll(file)
	if err != nil {
		return "", err
	}
	return string(data), nil
}